<template>
  <el-select
    ref="select"
    v-model="selectedValue"
    :clearable="clearable"
    :filterable="filterable"
    :placeholder="placeholder"
    :disabled="disabled"
    @visible-change="handleVisibleChange"
  >
    <el-option
      :value="selectedValue"
      :label="selectedLabel"
      style="height: auto; padding: 0"
    >
      <el-tree
        ref="tree"
        :data="regionTreeData"
        :props="treeProps"
        :node-key="nodeKey"
        :default-expanded-keys="defaultExpandedKeys"
        :highlight-current="highlightCurrent"
        :expand-on-click-node="false"
        @node-click="handleNodeClick"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span v-if="hasChildren(data)" class="node-arrow">
           <i :class="node.expanded ? 'el-icon-arrow-down' : 'el-icon-arrow-right'"></i>
          </span>
        </span>
      </el-tree>
    </el-option>
  </el-select>
</template>

<script>
// 完整的行政区划数据（示例）
import request from '@/utils/request'

export default {
  name: 'FixedRegionTreeSelect',
  props: {
    value: {
      type: [String, Number],
      default: ''
    },
    placeholder: {
      type: String,
      default: '请选择行政区划'
    },
    clearable: {
      type: Boolean,
      default: true
    },
    filterable: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    nodeKey: {
      type: String,
      default: 'value'
    },
    highlightCurrent: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      selectedValue: this.value,
      selectedLabel: '',
      regionTreeData: [],
      defaultExpandedKeys: [],
      treeProps: {
        value: 'value',
        label: 'label',
        children: 'children'
      }
    };
  },
  watch: {
    value(newVal) {
      this.selectedValue = newVal;
      this.updateSelectedLabel();
    }
  },
  created() {
    // 初始化时只展开省级节点
    this.init()

  },
  methods: {
    hasChildren(data) {
      return data.children && data.children.length > 0;
    },

    init(){
      this.getaa10({ aaa100:'AAB301' }).then(res => {
        const dataCopy = JSON.parse(JSON.stringify(res))
        this.regionTreeData = dataCopy
        // this.filteredTreeData = JSON.parse(JSON.stringify(this.regionTreeData));

        // this.defaultExpandedKeys = this.regionTreeData.map(item => item.value);
        this.updateSelectedLabel();
      })

    },

    getaa10(data) {
      return request({
        url: 'api/aa10/getaa10',
        method: 'post',
        data
      })
    },


    updateSelectedLabel() {
      if (!this.selectedValue) {
        this.selectedLabel = '';
        return;
      }

      const node = this.findNode(this.regionTreeData, this.selectedValue);
      this.selectedLabel = node ? node.label : '';
    },

    findNode(nodes, value) {
      for (const node of nodes) {
        if (node.value === value) {
          return node;
        }
        if (node.children) {
          const found = this.findNode(node.children, value);
          if (found) return found;
        }
      }
      return null;
    },

    handleNodeClick(data, node) {
      if (this.hasChildren(data)) {
        // 对于有子节点的项，切换展开状态
        if (node.expanded) {
          node.collapse();
        } else {
          node.expand();
        }
      } else {
        // 只有叶子节点（区级）才触发选中
        this.selectedValue = data.value;
        this.selectedLabel = data.label;
        this.$emit('input', data.value);
        this.$emit('change', data.value);
        this.$refs.select.blur();
      }
    },

    handleVisibleChange(visible) {
      if (visible) {
        this.$nextTick(() => {
          if (this.selectedValue) {
            this.$refs.tree.setCurrentKey(this.selectedValue);
          }
        });
      }
    }
  }
};
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.node-arrow {
  color: #999;
  font-size: 12px;
  margin-left: 8px;
}

.el-tree {
  max-height: 300px;
  overflow-y: auto;
  padding: 5px;
}

.el-select {
  width: 100%;
}
</style>
